package com.dqp.cslggroup.JWXT;

import android.Manifest;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.Spinner;
import androidx.appcompat.widget.Toolbar;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dqp.cslggroup.Api.jwxtApi;
import com.dqp.cslggroup.Api.xxmhApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.Features.Setting;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.SubjectView.MySubject;
import com.dqp.cslggroup.SubjectView.SubjectRepertory;
import com.dqp.cslggroup.UI.AlertDialog;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.*;
import com.dqp.cslggroup.bean.course;
import com.dqp.cslggroup.greendao.courseDao;
import com.zhuangfei.timetable.TimetableView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SearchCourse extends BaseActivity {
    private Spinner cx_spinner_year, cx_spinner_term;
    private Button cx_button;
    private Map<String, String> cookies;
    private String stuNum, use_url;
    private ViewStub viewstub_loading;
    private TimetableView timetableView;
    static String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.WRITE_CALENDAR,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    ExecutorService threadPool = Executors.newFixedThreadPool(2);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_course);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        stuNum = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
        getCookies();
        initCmp();
        submit();
    }


    private void initCmp() {
        cx_spinner_term = findViewById(R.id.course_term);
        cx_spinner_year = findViewById(R.id.course_year);
        cx_button = findViewById(R.id.course_submit);
        viewstub_loading = findViewById(R.id.viewstub_loading);
        timetableView = findViewById(R.id.search_timetableView);
        int month = GetTimeUtil.getMonth();
        int year = GetTimeUtil.getYear();
        if (month < 8 && month >= 2) {
            cx_spinner_year.setSelection(year - 2017);
            cx_spinner_term.setSelection(1);
        } else {
            if (month > 7) year++;
            cx_spinner_year.setSelection(year - 2017);
            cx_spinner_term.setSelection(0);
        }
    }

    private void submit() {
        cx_button.setOnClickListener(v -> {
            viewstub_loading.setVisibility(View.VISIBLE);
            new Thread(() -> {
                int year = cx_spinner_year.getSelectedItemPosition() + 2016;
                int term = cx_spinner_term.getSelectedItemPosition() + 1;
                JSONObject jsonObject = jwxtApi.course(stuNum, year, term, cookies);
                System.out.println(jsonObject);
                if (jsonObject != null && jsonObject.containsKey("courseList")) {
                    MyApplication.getDaoInstant().getCourseDao().queryBuilder().where(courseDao.Properties.Who.eq(0)).buildDelete().executeDeleteWithoutDetachingEntities();
                    JSONArray timeTable = JSON.parseArray(jsonObject.getString("courseList"));
                    List<course> courseList = new ArrayList<>();
                    for (Object o : timeTable) {
                        JSONObject lesson = (JSONObject) o;
                        course c = new course();
                        c = lesson.toJavaObject(course.class);
                        courseList.add(c);
                    }
                    if (courseList == null && courseList.size() == 0)
                        EventBus.getDefault().post(new MessageEvent("SearchCourse", 2, null));
                    else EventBus.getDefault().post(new MessageEvent("SearchCourse", 1, courseList));
                }

            }).start();

        });
    }

    public void getCookies() {
        Map<String, String> map = SharedPreferencesUtil.getMap(this, "cookies");
        long time = SharedPreferencesUtil.getLongSp(this, "cookiesTime", 0);
        long nowTime = GetTimeUtil.getCurrentTimeMillis();
        long x = GetTimeUtil.minuteDifference(nowTime, time);
        if (x < 10) {
            cookies = map;
        } else {
            String xxmh = SharedPreferencesUtil.getStringSp(this, "password_XXMH", null);
            String sno = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
            String jwxt = SharedPreferencesUtil.getStringSp(this, "password_JWXT", null);
            if (!StringUtil.isEmpty(xxmh, sno, jwxt)) {
                viewstub_loading.setVisibility(View.VISIBLE);
                threadPool.execute(() -> {
                    JSONObject jsonObject = xxmhApi.login(sno, xxmh, "0");
                    if (Result.jsonResultIsTure(jsonObject)) {
                        JSONObject object = jsonObject.getJSONObject("info");
                        Map<String, String> xxmhCookies = JSONObject.parseObject(object.toJSONString(), new TypeReference<Map<String, String>>() {
                        });
                        if (xxmhCookies == null || xxmhCookies.size() < 2) return;
                        object = jwxtApi.login(xxmhCookies, sno, jwxt, "0");
                        if (Result.jsonResultIsTure(object)) {
                            cookies = xxmhCookies;
                            CookiesUtil.save(this, cookies);
                        }
                    } else if (jsonObject.containsKey("resultMsg") && jsonObject.getJSONObject("resultMsg").containsKey("密码错误")) {
                        alertDialog("密码错误", "您绑定的信息门户账号密码错误，您近期是否进行了密码更改？" +
                                "现已无法正常使用该模块功能，为确保正常使用请前往设置重新绑定！");
                    }
                });
            } else {
                alertDialog("账号未绑定", "检测到您绑定的信息门户、教务系统账号或密码信息缺失，无法正常使用该模块功能，" +
                        "为确保正常使用请前往设置进行绑定！");
            }
        }
    }

    public void alertDialog(String title, String msg) {
        AlertDialog alertDialog = new AlertDialog(this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle(title)
                .setMsg(msg)
                .setMsgGravity(false)
                .setNegativeButton("设置", R.color.colorAccent, v1 -> {
                    alertDialog.dismiss();
                    UiUtils.startActivity(this, Setting.class);
                })
                .setPositiveButton("取消", R.color.colorAccent, v2 -> {
                    alertDialog.dismiss();
                    finish();
                })
                .show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("SearchCourse")) {
            switch (event.getWhat()) {
                case 1:
                    List<course> courseList = (List<course>) event.getObj();
                    if (courseList.size() > 0) {
                        List<MySubject> mySubjectList = SubjectRepertory.loadSubjects(courseList);
                        timetableView.curWeek(1)
                                .curTerm(cx_spinner_year.getSelectedItem().toString())
                                .maxSlideItem(10)
                                .monthWidthDp(25)
                                .itemHeight(180)
                                .source(mySubjectList)
                                .itemTextColor(Color.BLACK, true)
                                .isShowNotCurWeek(true)
                                .cornerAll(15)
                                .isShowWeekends(true)
                                .isShowFlaglayout(false)
                                .alpha(0f, 0f, 0.3f)
                                .showView();
                    }
                    viewstub_loading.setVisibility(View.GONE);
                    break;
                case 2:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("暂无数据！");
                    break;
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
